from django.views.decorators.csrf import csrf_exempt
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework import mixins, status
from rest_framework import viewsets
from rest_framework.decorators import action

from drf_yasg.utils import swagger_auto_schema

from api.utils.common import with_common_response, paginate_list
from django.db.models import ObjectDoesNotExist
from api.routes.user.login.serializer import (
    UserLoginRequestSerializer,
    UserNameRepeatCheckSerializer,
    MobileRepeatCheckSerializer,
    RepeatRepeatSerializer,
    UserBodySerializer,
    AddressQeurySerializer,
    AddressBobySerializer,
    UserAddressQeurySerializer,
    UserAddressBodySerializer,
    UserQuerySerializer,
    UserInfoSerializer,
    AddressQuerySerializer,
    AddressBodySerializer,
    AddressDataSerializer,
)
from api.models.user import User, ShipAddress, Address

from api.exceptions import ResourceNotFound
from api.auth import JWTAuthentication, ShopModelBackend


class UserLoginView(viewsets.ViewSet):
    @swagger_auto_schema(
        operation_summary="地址详情",
        operation_description="地址详情",
        query_serializer=AddressQuerySerializer,
        responses=with_common_response({status.HTTP_200_OK: AddressDataSerializer}),
    )
    @action(methods=["get"], url_name="address-info", url_path="address-info", detail=False)
    def address_info(self, request):
        serializer = AddressQuerySerializer(data=request.GET)
        if serializer.is_valid(raise_exception=True):
            username = serializer.validated_data.get("username")
            default = serializer.validated_data.get("default")
            page = serializer.validated_data.get("page")
            per_page = serializer.validated_data.get("per_page")
            query_body = {}
            if username:
                query_body.update({"user__username": username})
            if default:
                query_body.update({"default": default})

            try:
                shop_address = ShipAddress.objects.filter(**query_body)
            except ObjectDoesNotExist as e:
                raise ResourceNotFound(detail="地址未找到")

            data, total = paginate_list(shop_address, page, per_page)

            respesen = AddressDataSerializer({"total": total, "data": data})

            return Response(status=status.HTTP_200_OK, data=respesen.data)

    @swagger_auto_schema(
        operation_summary="用户详情",
        operation_description="用户详情",
        query_serializer=UserQuerySerializer,
        responses=with_common_response({status.HTTP_200_OK: UserInfoSerializer}),
    )
    @action(methods=["get"], url_name="user-info", url_path="user-info", detail=False)
    def user_info(self, request):
        serializer = UserQuerySerializer(data=request.GET)
        if serializer.is_valid(raise_exception=True):
            username = serializer.validated_data.get("username")

            try:
                user = User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise ResourceNotFound(detail="用户未找到")

            respesen = UserInfoSerializer(user)

            return Response(status=status.HTTP_200_OK, data=respesen.data)

    @swagger_auto_schema(
        operation_summary="创建用户",
        operation_description="创建用户",
        request_body=UserLoginRequestSerializer,
        responses=with_common_response({status.HTTP_201_CREATED: ""}),
    )
    def create(self, request):
        """用户注册"""
        serializer = UserLoginRequestSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            username = serializer.validated_data.get("username")
            mobile = serializer.validated_data.get("mobile")
            password = serializer.validated_data.get("password")
            allow = serializer.validated_data.get("allow")

        try:
            user = User.objects.create_user(
                username=username, mobile=mobile, password=password, is_active=allow
            )
        except ObjectDoesNotExist:
            raise ResourceNotFound(detail="用户创建失败")

        response = UserBodySerializer(user)

        return Response(status=status.HTTP_201_CREATED, data=response.data)

    @swagger_auto_schema(
        method="get",
        operation_summary="检查用户名是否重复",
        operation_description="检查用户名是否重复",
        query_serializer=UserNameRepeatCheckSerializer,
        responses=with_common_response({status.HTTP_200_OK: RepeatRepeatSerializer}),
    )
    @action(methods=["get"], url_name="name-repeat", url_path="names", detail=False)
    def username_repeat_check(self, request):
        serializer = UserNameRepeatCheckSerializer(data=request.GET)
        if serializer.is_valid(raise_exception=True):
            username = serializer.validated_data.get("username")
            try:
                user = User.objects.get(username=username)
            except ObjectDoesNotExist:
                raise ResourceNotFound(detail="用户不存在")

            response = RepeatRepeatSerializer({"mob": user.id})
            return Response(status=status.HTTP_200_OK, data=response.data)

    @swagger_auto_schema(
        method="get",
        operation_summary="检查手机号是否重复",
        operation_description="检查手机号是否重复",
        query_serializer=MobileRepeatCheckSerializer,
        responses=with_common_response({status.HTTP_200_OK: RepeatRepeatSerializer}),
    )
    @action(methods=["get"], url_name="mobile-repeat", url_path="mobiles", detail=False)
    def mobile_repeat_check(self, request):
        serializer = MobileRepeatCheckSerializer(data=request.GET)
        if serializer.is_valid(raise_exception=True):
            mobile = serializer.validated_data.get("mobile")
            try:
                mob = User.objects.get(mobile=mobile)
            except ObjectDoesNotExist:
                raise ResourceNotFound(detail="手机号不存在")

            response = RepeatRepeatSerializer({"mob": mob.id})

            return Response(status=status.HTTP_200_OK, data=response.data)


class UserAddressView(viewsets.ViewSet):
    permission_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_summary="添加用户地址",
        operation_description="添加用户地址",
        request_body=UserAddressQeurySerializer,
        responses=with_common_response({status.HTTP_201_CREATED: UserAddressBodySerializer}),
    )
    @action(methods=["POST"], url_name="add-address", url_path="add-address", detail=False)
    def shop_address(self, request):
        serializer = UserAddressQeurySerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            address_id = serializer.validated_data.get("address_id")
            province = serializer.validated_data.get("province")
            city = serializer.validated_data.get("city")
            area = serializer.validated_data.get("area")
            detailed = serializer.validated_data.get("detailed")
            default = serializer.validated_data.get("default")

            if default:
                for ship_address in ShipAddress.objects.filter(user=request.user, default=True):
                    ship_address.default = False
                    ship_address.save()
            if address_id:
                num = ShipAddress.objects.filter(id=address_id).update(
                    province=province, city=city, area=area, detailed=detailed, default=default
                )
                if num:
                    ship_address = ShipAddress.objects.get(id=address_id)

            else:

                ship_address = ShipAddress.objects.create(
                    user=request.user,
                    province=province,
                    city=city,
                    area=area,
                    default=default,
                    detailed=detailed,
                )

            response = UserAddressBodySerializer(ship_address)

            return Response(status=status.HTTP_201_CREATED, data=response.data)

    @swagger_auto_schema(
        method="get",
        operation_summary="地址列表",
        operation_description="地址列表",
        query_serializer=AddressQeurySerializer,
        responses=with_common_response({status.HTTP_200_OK: AddressBobySerializer}),
    )
    @action(methods=["get"], url_name="address", url_path="address", detail=False)
    def address_list(self, request):
        serializer = AddressQeurySerializer(data=request.GET)
        if serializer.is_valid(raise_exception=True):
            parent_number = serializer.validated_data.get("parent_number", 0)

            addresses = Address.objects.filter(parent_number=parent_number)

        response = AddressBobySerializer(addresses, many=True)

        return Response(status=status.HTTP_200_OK, data=response.data)
